﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Media;
using VtcPositionDemo.Driver;
using VtcPositionDemo.Common.Models;
using VtcPositionDemo.Common.MvvmLight;
using System.Windows;
using MyFIFO;
using Newtonsoft.Json.Linq;
using System.Collections.Concurrent;
using System.Windows.Input;
using System.Timers;
using Quobject.Collections.Immutable;
using Quobject.SocketIoClientDotNet.Client;
using VtcPositionDemo.Models;
using VtcPositionDemo.Viewmodel.Dto;
using VtcPositionDemo.Common.Utils;
using System.Data;

namespace VtcPositionDemo.ViewModel
{

    public enum MainWindowState
    {
        INIT,
        UP,
        STOP,
        DOWN,
        START,
        POSITION
    }



    public class MainWindowViewModel : ViewModelBase
    {

        public DataTable dataTableCsv = new DataTable();

        public BtnStatus _btnStatus;
        public BtnStatus btnStatus
        {
            get { return _btnStatus; }
            set
            {

                _btnStatus = value;
                RaisePropertyChanged();
            }

        }


        public VtcRobot m_robot = new VtcRobot();
        private bool _isSavaLog=false;
        public bool isSavaLog
        {
            get { return _isSavaLog; }
            set
            {
                if(m_robot.State== RunState.INIT || m_robot.State == RunState.CLOSED)
                {
                    _isSavaLog = value;
                    RaisePropertyChanged();
                }
                else
                {
                    MessageBox.Show("运行中");
                }
            }
        }


        private double _speed;
        public double speed
        {
            get { return _speed; }
            set
            {
                if (m_robot.State == RunState.INIT)
                {
                    MessageBox.Show("未启动");
                    return;
                }
                m_robot.setSpeed(value);
            }
        }

        public MainWindow mainWindow;
        private List<string> _filechangeMsglist;
        public List<string> filechangeMsglist
        {
            get { return _filechangeMsglist; }
            set
            {
                _filechangeMsglist = value;
                RaisePropertyChanged();
            }
        }

        public MainWindowState mainWindowState { get; private set; }



        private long _time;
        public long time
        {
            get { return _time; }
            set
            {
                _time = value;
                RaisePropertyChanged();
            }
        }


        private double _disp;
        public double disp
        {
            get { return _disp; }
            set
            {
                _disp = value;
                RaisePropertyChanged();
            }
        }



        private string _do0Color;
        public string do0Color
        {
            get
            {
                return _do0Color;
            }
            set
            {
                _do0Color = value;
                RaisePropertyChanged();
            }
        }



        public string resetColor
        {
            get {
                if (mainWindowState == MainWindowState.STOP)
                {
                    return "red";
                }
                else
                {
                    return "white";
                }
            ; }
            set
            {
                RaisePropertyChanged();
            }
        }





        private Timer m_timer = new Timer();

        public MainWindowViewModel(MainWindow mainWindow)
        {
            this.mainWindow = mainWindow;
            mainWindowState = MainWindowState.INIT;
            btnStatus = new BtnStatus(mainWindowState);
            AtsPushButton = new RelayCommand<string>(AtsPushButtonHandel);
            Launch = new RelayCommand<string>(LaunchHandel);
            AtsLoad = new RelayCommand<string>(AtsLoadHandel);
            AtsStart = new RelayCommand<string>(AtsStartHandel);
            HandRun = new RelayCommand<string>(HandRunHandel);
            RunStart = new RelayCommand<string>(RunStartHandel);
            RunAtsTerminate = new RelayCommand<string>(RunAtsTerminateHandel);
            RunDo = new RelayCommand<string>(RunDoHandel);
            dataTableCsv.Columns.Add("ms", typeof(int));//主键编号
            dataTableCsv.Columns.Add("disp", typeof(double));//姓名

            filechangeMsglist = new List<string>();
            this.m_robot.OnRobotEvent += M_robot_OnRobotEvent;
            this.m_timer.Interval = 500;
            this.m_timer.Elapsed += M_timer_Tick;
            this.m_timer.Start();

        }



        /// <summary>
        /// socket 发出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void M_timer_Tick(object sender, EventArgs e)
        {
            HandleVinResult handleVinResult = new HandleVinResult();
            handleVinResult.disp = new List<double>();
            handleVinResult.time = new List<long>();
            ChannelDisMsg cm = null;
            while (channelQueue.TryDequeue(out cm))
            {
                cm.dispAd = Math.Round(cm.dispAd, 3);
                handleVinResult.disp.Add(cm.dispAd);
                handleVinResult.time.Add(cm.ms);
                //满20个发给页面
                if (handleVinResult.disp.Count >= 20)
                {
                    JObject jsonObject = JObject.FromObject(handleVinResult);
                    handleVinResult.disp.Clear();
                    handleVinResult.time.Clear();
                }
            }
        }

        private ConcurrentQueue<ChannelDisMsg> channelQueue = new ConcurrentQueue<ChannelDisMsg>();



       
    public ICommand AtsPushButton { get; set; }
        public void AtsPushButtonHandel(String args)
        {
            if ( m_robot.State != RunState.ATS_RUNING)
            {
                MessageBox.Show("未启动");
                return;
            }

            m_robot.AtsPushButton(args);
        }

        


        public ICommand Launch { get; set; }
        public void LaunchHandel(String args)
        {
            m_robot.Launch();
        }

        public ICommand AtsLoad { get; set; }
        public void AtsLoadHandel(String args)
        {
            m_robot.AtsLoad();
        }


        public ICommand AtsStart { get; set; }
        public void AtsStartHandel(String args)
        {
            dataTableCsv.Rows.Clear();
            m_robot.RunAtsStart();
        }

        public ICommand HandRun { get; set; }
        public void HandRunHandel(String args)
        {
           m_robot.HandPushButton(args);
        }




        public ICommand RunStart { get; set; }
        public void RunStartHandel(String args)
        {
            m_robot.RunStart();
            dataTableCsv.Rows.Clear();
        }

        public ICommand RunAtsTerminate { get; set; }
        public void RunAtsTerminateHandel(String args)
        {
            m_robot.RunAtsTerminate();
        }


        public ICommand RunDo { get; set; }
        public void RunDoHandel(String args)
        {
            switch (args)
            {
                case"do0":{
                        if (do0Color == BtnColorEnum.DISABLE)
                        {
                            do0Color = BtnColorEnum.ENABLE;
                            m_robot.VtcSwitchOn("#do0", true);
                        }
                        else
                        {
                            do0Color = BtnColorEnum.DISABLE;
                            m_robot.VtcSwitchOn("#do0", false);
                        }
                       break;
                 }
                case "doOutPut":
                    {
                      
                        break;
                    }
                    

            }
        }





        public void changeBtnColor(string btName)
        {
            switch (btName)
            {
                case "move_up":
                    {
                        mainWindowState = MainWindowState.UP;
                        break;
                    };
                case "move_down":
                    {
                        mainWindowState = MainWindowState.DOWN;
                        break;
                    };
                case "pause":
                    {
                        mainWindowState = MainWindowState.STOP;
                        break;
                    };
                case "start":
                    {
                        mainWindowState = MainWindowState.START;
                        break;
                    };
                case "position":
                    {
                        mainWindowState = MainWindowState.POSITION;
                        break;
                    };
            }

            btnStatus = new BtnStatus(mainWindowState);
        }


 

        public static long msgCount = 0;


        private void M_robot_OnRobotEvent(object sender, VtcRobot.RobotEventArgs e)
        {
            switch (e.mType)
            {
                case VtcRobot.RobotEventType.VtcMsg:
                    {
                        var cm = (VtcMsg)e.mVal;
                        this.mainWindow.Dispatcher.BeginInvoke(
                                          new Action(
                                           delegate
                                           {
                                               msgCount++;
                                               String s = $"{msgCount}:(0x{Convert.ToString(cm.MsgId, 16)}){cm.Msg}";
                                               filechangeMsglist.Add(s);
                                               filechangeMsglist = new List<string>(filechangeMsglist);
                                               Decorator decorator = (Decorator)VisualTreeHelper.GetChild(this.mainWindow.msgListBox, 0);
                                               ScrollViewer scrollViewer = (ScrollViewer)decorator.Child;
                                               scrollViewer.ScrollToEnd();
                                           }
                                       ));

                        if (cm.MsgId == vtc.ATS_OVER1 && isSavaLog)
                        {
                            if (dataTableCsv.Rows.Count>0)
                            {
                                CSVHelper.SaveToCSV(dataTableCsv,"testlog/"+ DateUtils.DATE_TIME_UNDERLINE.Now()+".csv");
                            }
                         
                        }



                         break;
                    }
               
                case VtcRobot.RobotEventType.PushBtn:
                    {
                        var btnName = (string)e.mVal;
                        changeBtnColor(btnName);
                        break;
                    }

                case VtcRobot.RobotEventType.ReadData:
                    {
                        ChannelTransmitMsg chanelMsg = (ChannelTransmitMsg)e.mVal;
                        this.time = chanelMsg.ms;
                        this.disp = Data.Data_Dvb2Float(chanelMsg.dispAd);
                        this.mainWindow.myUserControlWavw.chanelMsgWaveQueue.PushUnit(chanelMsg);
                        break;
                    }
                case VtcRobot.RobotEventType.SpeedChange:
                    {
                        double v = (double)e.mVal;
                        this.speed = v;
                        break;
                    }
            }
        }
    }
}
